package encryption

import (
	"bytes"
	"crypto/md5"
	"crypto/sha1"
	"encoding/base64"
	"fmt"
	"io"
	"math/rand"
	"strconv"
	"time"
)


//MD5加密字符串，用于密码使用
func GenMd5Password(pwd string) (newpwd string, err error) {

	md5Password := md5.New()
	_ , err = io.WriteString(md5Password, pwd)
	if err != nil {
		return newpwd, err
	}
	buffer := bytes.NewBuffer(nil)
	_, err = fmt.Fprintf(buffer, "%x", md5Password.Sum(nil))
	if err != nil {
		return newpwd, err
	}
	newpwd = buffer.String() //赋值md5加密的密码

	return newpwd, err
}

//MD5加密
func MD5(s string) string {
	return fmt.Sprintf("%x", md5.Sum([]byte(s)))
}

//SHA1加密
func Sha1(s string) string {
	return fmt.Sprintf("%x", sha1.Sum([]byte(s)))
}

//base64编码
//func Base64Encode(src []byte) []byte {
//	return []byte(base64.StdEncoding.EncodeToString(src))
//}
func Base64Encode(src string) string {
	return base64.StdEncoding.EncodeToString([]byte(src))
}

//base64解码
//func Base64Decode(src []byte)([]byte, error)  {
//	return base64.StdEncoding.DecodeString(string(src))
//}
func Base64Decode(src string) string {
	res, _ := base64.StdEncoding.DecodeString(src)
	return string(res)
}

//生成Token
func GenToken() string {
	curtime := time.Now().Unix()
	h := md5.New()
	io.WriteString(h, strconv.FormatInt(curtime, 10))
	return fmt.Sprintf("%x", h.Sum(nil))

}

//密码
func GenPassword(s string) string {
	salt := strconv.FormatInt(time.Now().UnixNano()%9000+1000, 10)
	return Base64Encode(Sha1(MD5(s)+salt) + salt)
}

//x的n次方
func Index(x int, n int) (val int) {
	val = 1
	for i := 0; i < n; i++ {
		val *= x
	}
	return val
}

//获取Code
func GenCode(n int) string {
	rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
	tmp := strconv.FormatInt(rnd.Int63n(int64(Index(10, n))), 10) //base进制
	for i := len(tmp); i < n; i++ {
		tmp = "0" + tmp
	}
	return tmp
}


//RandomStr 随机生成字符串
func RandomString(length int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < length; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}



